/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import AuthorizedNoMatch from "./AuthorizedNoMatch";

// 获取权限列表
export function getAuthority() {
  if (window.g_app) {
    const { global: { authority } = {} } = window.g_app._store.getState();
    return () => authority;
  }
}

// 设置权限列表
export function setAuthority(authority) {
  if (window.g_app) {
    window.g_app._store.dispatch({
      type: "global/changeAuthority",
      payload: { ...authority },
    });
  }
}

// 自定义权限控制处理
export function checkAuthority(currentAuthority, currentRouter, fromMenu, HIDE_WHILE_NO_AUTHORITY) {
  if (!currentRouter || !currentAuthority) return false;
  const { isRoot = false, root = [], sub = [] } = currentAuthority || {};
  const { authority } = currentRouter;
  if (!authority && isRoot) {
    // 主账号，没有填写权限的路由全部可访问；
    return true;
  }
  // 是否在主账号允许权限内
  const isInRoot = root.length === 0 || root.includes(authority);
  const isInSub = sub.length === 0 || sub.includes(authority);
  // 必须隐藏菜单的主账号
  const isInHide = !isInRoot && HIDE_WHILE_NO_AUTHORITY.includes(authority);
  // 菜单，非主账号或在必须隐藏的列表里才会隐藏
  return isRoot ? (fromMenu ? !isInHide : isInRoot) : isInRoot && isInSub;
}

export default AuthorizedNoMatch;
